package com.adcc.sgs.gcs.db;

import com.adcc.ags.utility.log.Log;
import io.dropwizard.lifecycle.Managed;
import io.dropwizard.setup.Environment;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.Reader;

/**
 * Created by nk on 2016/8/17.
 */
public class DBAccess implements Managed {

    private String dbResource;

    // SqlSessionFactory
    private SqlSessionFactory sessionFactory;

    public void build(Environment environment, String dbResource) throws Exception {
        this.dbResource = dbResource;
        environment.lifecycle().manage(this);
    }

    @Override
    public void start() throws Exception {
        Reader reader = null;
        try {
            reader = Resources.getResourceAsReader(this.dbResource);
            sessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (Exception ex) {
            Log.error(DBAccess.class.getName(), "start() error", ex);
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
    }

    @Override
    public void stop() throws Exception {

    }

    public SqlSessionFactory getSessionFactory() {
        return sessionFactory;
    }
}
